<template>
  <div class="virtual-classroom-page">
    <!-- 顶部标题区域 -->
    <div class="page-header mb-6">
      <h2 class="title">虚拟教室成绩管理</h2>
      <p class="desc">查看和管理学生在虚拟教室中的训练成绩和学习数据</p>
    </div>

    <!-- 搜索与操作区 -->
    <el-card class="search-card mb-6">
      <div class="search-container">
        <el-row :gutter="24">
          <!-- 搜索与筛选 -->
          <el-col :span="24">
            <el-row :gutter="24">
              <el-col :span="6" style="min-width: 200px;">
                <el-input
                  v-model="searchForm.studentName"
                  placeholder="搜索学生姓名"
                  prefix-icon="el-icon-user"
                  clearable
                  @keyup.enter.native="handleSearch"
                ></el-input>
              </el-col>
              <el-col :span="6" style="min-width: 200px;">
                <el-input
                  v-model="searchForm.studentPhone"
                  placeholder="搜索学生电话"
                  prefix-icon="el-icon-phone"
                  clearable
                  @keyup.enter.native="handleSearch"
                ></el-input>
              </el-col>
              <el-col :span="4" style="min-width: 200px;">
                <el-button 
                  type="primary"
                  icon="el-icon-search"
                  @click="handleSearch"
                >
                  搜索
                </el-button>
                <el-button 
                  @click="resetFilter"
                >
                  重置
                </el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 学习成果列表 -->
    <el-card>
      <!-- 暂时隐藏导出数据按钮 -->
      <el-table
        :data="resultList"
        v-loading="loading"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa' }"
        class="result-table"
      >
        <!-- 序号列 -->
        <el-table-column
          prop="id"
          label="学生ID"
          width="80"
          align="center"
        ></el-table-column>

        <!-- 学生姓名列 -->
        <el-table-column
          prop="studentName"
          label="学生姓名"
          min-width="120"
        ></el-table-column>

        <!-- 联系电话列 -->
        <el-table-column
          prop="phone"
          label="联系电话"
          min-width="140"
        >
          <template slot-scope="scope">
            {{ formatPhone(scope.row.phone) }}
          </template>
        </el-table-column>

        <!-- 训练项目列 -->
        <el-table-column
          prop="courseName"
          label="训练项目"
          min-width="160"
        ></el-table-column>

        <!-- 状态列 -->
        <el-table-column
          label="状态"
          min-width="140"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :class="['status-tag', `status-${scope.row.status}`]"
              size="small"
            >
              <!-- <span
                v-if="scope.row.status === 'active'"
                class="status-dot pulse-animation mr-1"
              ></span> -->
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 开始时间列 -->
        <el-table-column
          prop="startTime"
          label="开始时间"
          min-width="160"
        >
          <template slot-scope="scope">
            {{ scope.row.startTime || '-' }}
          </template>
        </el-table-column>

        <!-- 结束时间列 -->
        <el-table-column
          prop="endTime"
          label="结束时间"
          min-width="160"
        >
          <template slot-scope="scope">
            {{ scope.row.endTime || '-' }}
          </template>
        </el-table-column>

        <!-- 成绩列 -->
        <el-table-column
          label="成绩"
          min-width="100"
          align="center"
        >
          <template slot-scope="scope">
            <span
              v-if="scope.row.score"
              :class="getScoreClass(scope.row.score)"
              class="score-text"
            >
              {{ scope.row.score }}分
            </span>
            <span v-else class="text-gray-500">-</span>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column
          label="学习资料"
          min-width="180"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              :disabled="!scope.row.score"
              :class="{ 'text-gray-400': !scope.row.score, 'text-primary': scope.row.score }"
              @click="openReportModal(scope.row)"
            >
              报告
            </el-button>
            <el-button
              type="text"
              size="small"
              :disabled="!scope.row.score"
              :class="{ 'text-gray-400': !scope.row.score, 'text-purple': scope.row.score }"
              @click="openVideoModal(scope.row)"
            >
              回放
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50]"
          :page-size="pagination.size"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 学习报告模态框 -->
    <el-dialog
      :title="reportTitle"
      :visible.sync="reportModalVisible"
      width="800px"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
    >
      <div class="report-container">
        <!-- 基础信息卡片 -->
        <el-row :gutter="20" class="mb-6">
          <el-col :span="8">
            <el-card class="info-card">
              <div class="info-label">训练项目</div>
              <div class="info-value">{{ currentReport.courseName }}</div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="info-card">
              <div class="info-label">训练时间</div>
              <div class="info-value">
                {{ currentReport.startTime }} - {{ currentReport.endTime }}
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="info-card">
              <div class="info-label">最终成绩</div>
              <div class="info-value score-value">
                {{ currentReport.score }}分
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 焊接成果图片 -->
        <div class="mb-6">
          <h4 class="section-title">焊接成果图片</h4>
          <el-row :gutter="20" class="mt-3">
            <el-col :span="12">
              <el-card class="image-card">
                <img
                  :src="currentReport.images && currentReport.images[0] ? currentReport.images[0] : ''"
                  alt="焊缝正面图"
                  class="w-full h-48 object-cover"
                >
                <div class="image-desc">焊缝正面图</div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="image-card">
                <img
                  :src="currentReport.images && currentReport.images[1] ? currentReport.images[1] : ''"
                  alt="焊缝侧面图"
                  class="w-full h-48 object-cover"
                >
                <div class="image-desc">焊缝侧面图</div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 技能评估详情 -->
        <div class="mb-6">
          <h4 class="section-title">技能评估详情</h4>
          <el-card class="assessment-card mt-3">
            <div class="assessment-list">
              <div class="assessment-item" v-for="(item, index) in currentReport.assessment" :key="index">
                <div class="item-header">
                  <span class="item-name">{{ item.name }}</span>
                  <span class="item-score">{{ item.score }}分</span>
                </div>
                <el-progress
                  :percentage="item.score"
                  :color="getProgressColor(item.score)"
                  height="6"
                  class="mt-1"
                ></el-progress>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 教师评语 -->
        <div>
          <h4 class="section-title">教师评语</h4>
          <el-card class="comment-card mt-3">
            <div class="comment-content">
              {{ currentReport.comment || '暂无评语' }}
            </div>
          </el-card>
        </div>
      </div>
      
      <div slot="footer" class="report-footer">
        <el-button type="primary" icon="el-icon-print" @click="printReport">
          打印报告
        </el-button>
      </div>
    </el-dialog>

    <!-- 视频回放模态框 -->
    <el-dialog
      :title="videoTitle"
      :visible.sync="videoModalVisible"
      width="900px"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      class="video-modal"
    >
      <div class="video-container">
        <!-- 视频播放区域 -->
        <div class="video-player">
          <div class="player-bg">
            <img
              :src="currentVideo.cover ? currentVideo.cover : ''"
              alt="视频封面"
              class="w-full h-full object-cover"
            >
            <!-- 播放按钮 -->
            <div class="play-btn" @click="playVideo">
              <i class="el-icon-play"></i>
            </div>
            <!-- 进度条 -->
            <div class="progress-bar">
              <div class="progress-track"></div>
              <div class="progress-current" :style="{ width: videoProgress + '%' }"></div>
            </div>
            <!-- 时间显示 -->
            <div class="time-display">
              <span class="current-time">{{ formatTime(videoCurrentTime) }}</span>
              <span class="total-time">{{ formatTime(videoTotalTime) }}</span>
            </div>
          </div>
        </div>

        <!-- 视频信息 -->
        <el-row :gutter="20" class="video-info mt-6 mb-6">
          <el-col :span="8">
            <div class="info-label">训练项目</div>
            <div class="info-value">{{ currentVideo.courseName }}</div>
          </el-col>
          <el-col :span="8">
            <div class="info-label">训练日期</div>
            <div class="info-value">{{ currentVideo.date }}</div>
          </el-col>
          <el-col :span="8">
            <div class="info-label">训练时长</div>
            <div class="info-value">{{ currentVideo.duration }}</div>
          </el-col>
        </el-row>

        <!-- 关键时间点 -->
        <div>
          <h4 class="section-title">关键时间点</h4>
          <el-card class="timeline-card mt-3">
            <div class="timeline-list">
              <el-button
                type="text"
                class="timeline-item"
                v-for="(item, index) in currentVideo.timeline"
                :key="index"
                @click="jumpToTime(item.time)"
              >
                <div class="item-content">
                  <div class="item-title">{{ item.title }}</div>
                  <div class="item-desc">{{ item.time }} - {{ item.desc }}</div>
                </div>
                <i class="el-icon-play-circle item-icon"></i>
              </el-button>
            </div>
          </el-card>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api'

export default {
  data() {
    return {
      // 搜索筛选表单
      searchForm: {
        studentName: '',
        studentPhone: ''
      },

      // 学习成果列表数据
      resultList: [],
      loading: false,

      // 分页配置
      pagination: {
        page: 1,
        size: 10,
        total: 0
      },

      // 模态框状态
      reportModalVisible: false,
      videoModalVisible: false,
      reportTitle: '',
      videoTitle: '',

      // 当前查看的报告/视频数据
      currentReport: {},
      currentVideo: {},

      // 视频播放相关
      videoProgress: 45,
      videoCurrentTime: 2730, // 秒数：45分30秒
      videoTotalTime: 3000,   // 秒数：50分钟

      // 模拟数据 - 学习报告
      reportDataMap: {},

      // 模拟数据 - 视频回放
      videoDataMap: {}
    };
  },
  
  mounted() {
    // 初始化加载成绩列表
    this.getScoreList()
  },
  
  methods: {
    // 获取成绩列表
    async getScoreList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.page,
          page_size: this.pagination.size
        }
        
        // 只添加有值的搜索参数
        if (this.searchForm.studentName) {
          params.student_name = this.searchForm.studentName
        }
        if (this.searchForm.studentPhone) {
          params.student_phone = this.searchForm.studentPhone
        }
        
        const res = await api.virtualClassroom.getVirtualScores(params)
        
        if (res && res.code === 200) {
          const list = Array.isArray(res.data?.list) ? res.data.list : (Array.isArray(res.data) ? res.data : [])
          
          this.resultList = list.map(item => ({
            id: item.id,
            studentName: item.student?.name || '',
            phone: item.student?.phone || '',
            courseName: item.project_name || '',
            status: String(item.status), // 转为字符串: '0', '1', '2'
            startTime: item.start_time || '',
            endTime: item.end_time || '',
            score: item.score || ''
          }))
          
          // 兼容两种分页格式
          if (res.pagination) {
            this.pagination.total = res.pagination.total || 0
            this.pagination.page = res.pagination.page || this.pagination.page
            this.pagination.size = res.pagination.page_size || this.pagination.size
          } else if (res.data) {
            this.pagination.total = res.data.total || 0
            this.pagination.page = res.data.page || this.pagination.page
            this.pagination.size = res.data.page_size || this.pagination.size
          }
        }
      } catch (error) {
        this.$message.error('获取成绩列表失败')
      } finally {
        this.loading = false
      }
    },
    
    // 格式化手机号（中间四位打码）
    formatPhone(phone) {
      if (!phone) return '';
      return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3');
    },

    // 状态文本映射
    getStatusText(status) {
      const statusMap = {
        '0': '未开始',
        '1': '进行中',
        '2': '已完成',
        0: '未开始',
        1: '进行中',
        2: '已完成'
      }
      return statusMap[status] || '未知状态'
    },

    // 成绩样式映射
    getScoreClass(score) {
      if (score >= 85) return 'text-success font-medium';
      if (score >= 60) return 'text-warning font-medium';
      return 'text-danger font-medium';
    },

    // 进度条颜色映射
    getProgressColor(score) {
      if (score >= 85) return '#00B42A';
      if (score >= 60) return '#FF7D00';
      return '#F53F3F';
    },

    // 搜索方法
    handleSearch() {
      this.pagination.page = 1
      this.getScoreList()
    },

    // 重置筛选条件
    resetFilter() {
      this.searchForm = {
        studentName: '',
        studentPhone: ''
      }
      this.pagination.page = 1
      this.getScoreList()
    },

    // 导出数据
    exportData() {
      this.$message.info('正在导出学习成果数据，请稍后...');
      // 实际项目中调用导出接口
    },

    // 打开学习报告模态框
    openReportModal(row) {
      this.currentReport = this.reportDataMap[row.id] || {};
      this.reportTitle = `焊接学习报告 - ${this.currentReport.studentName}`;
      this.reportModalVisible = true;
    },

    // 打开视频回放模态框
    openVideoModal(row) {
      this.currentVideo = this.videoDataMap[row.id] || {};
      this.videoTitle = `焊接练习回放 - ${this.currentVideo.studentName}`;
      this.videoModalVisible = true;
    },

    // 打印报告
    printReport() {
      this.$message.info('正在准备打印学习报告...');
      // 实际项目中调用打印接口或触发打印事件
    },

    // 视频播放相关方法
    playVideo() {
      this.$message.info('视频开始播放');
      // 实际项目中调用视频播放接口
    },

    // 跳转到指定时间点
    jumpToTime(time) {
      const [min, sec] = time.split(':').map(Number);
      const totalSec = min * 60 + sec;
      this.videoCurrentTime = totalSec;
      this.videoProgress = Math.round((totalSec / this.videoTotalTime) * 100);
      this.$message.info(`已跳转到 ${time}`);
    },

    // 格式化时间（秒转分:秒）
    formatTime(seconds) {
      const min = Math.floor(seconds / 60);
      const sec = Math.floor(seconds % 60);
      return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
    },

    // 分页相关方法
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.page = 1
      this.getScoreList()
    },
    handleCurrentChange(page) {
      this.pagination.page = page
      this.getScoreList()
    }
  }
}
</script>

<style scoped>
/* 页面基础样式 */
.virtual-classroom-page {
  width: 100%;
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
  text-align: left;
}
.title {
  font-size: 20px;
  font-weight: bold;
  color: #304156;
  margin-bottom: 5px;
}
.desc {
  color: #86909C;
  font-size: 14px;
}

/* 搜索区 */
.search-card {
  padding: 15px 20px;
}
.search-container {
  width: 100%;
}

/* 表格头部 */
.table-header {
  margin-bottom: 16px;
  text-align: left;
}

/* 清除浮动 */
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

/* 筛选区样式 */
.filter-card {
  padding: 15px 20px;
}
.full-width {
  width: 100% !important;
}

/* 成果列表样式 */
.result-table {
  width: 100%;
}
.status-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.status-0 {
  background-color: #F3F4F6;
  color: #6B7280;
  border-color: #F3F4F6;
}
.status-1 {
  background-color: #D1FAE5;
  color: #059669;
  border-color: #D1FAE5;
}
.status-2 {
  background-color: #E6F4FF;
  color: #165DFF;
  border-color: #E6F4FF;
}
.status-dot {
  display: inline-block;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background-color: #00B42A;
}
.pulse-animation {
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}
.score-text {
  font-size: 13px;
  font-weight: 500;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 报告模态框样式 */
.report-container {
  padding: 10px 0;
}
.info-card {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 12px;
}
.info-label {
  font-size: 12px;
  color: #86909C;
  margin-bottom: 4px;
}
.info-value {
  font-size: 14px;
  font-weight: 500;
  color: #304156;
}
.score-value {
  color: #00B42A;
  font-size: 16px;
}
.section-title {
  font-size: 15px;
  font-weight: 500;
  color: #304156;
  padding-left: 8px;
  border-left: 2px solid #165DFF;
}
.image-card {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  overflow: hidden;
}
.image-desc {
  text-align: center;
  padding: 8px;
  background-color: #F5F7FA;
  font-size: 12px;
  color: #6B7280;
}
.assessment-card {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 16px;
}
.assessment-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.assessment-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.item-header {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #4E5969;
}
.item-name {
  font-weight: 500;
}
.item-score {
  font-weight: 500;
}
.comment-card {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 16px;
  background-color: #F5F7FA;
}
.comment-content {
  font-size: 14px;
  color: #4E5969;
  line-height: 1.6;
}
.report-footer {
  text-align: right;
  padding: 12px 20px;
  border-top: 1px solid #F2F3F5;
}

/* 视频模态框样式 */
.video-modal {
  --video-height: 400px;
}
.video-container {
  padding: 10px 0;
}
.video-player {
  width: 100%;
  height: var(--video-height);
}
.player-bg {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #000;
  border-radius: 4px;
  overflow: hidden;
}
.play-btn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: rgba(22, 93, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
}
.play-btn:hover {
  background-color: rgba(22, 93, 255, 1);
}
.play-btn i {
  color: #fff;
  font-size: 24px;
  margin-left: 4px;
}
.progress-bar {
  position: absolute;
  bottom: 30px;
  left: 0;
  right: 0;
  height: 4px;
  padding: 0 16px;
}
.progress-track {
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
}
.progress-current {
  height: 100%;
  background-color: #165DFF;
  border-radius: 2px;
}
.time-display {
  position: absolute;
  bottom: 10px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  padding: 0 16px;
  color: #fff;
  font-size: 12px;
}
.video-info {
  margin-top: 16px;
}
.timeline-card {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 16px;
}
.timeline-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.timeline-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  width: 100%;
  text-align: left;
  transition: all 0.2s;
}
.timeline-item:hover {
  border-color: #165DFF;
  background-color: rgba(22, 93, 255, 0.05);
}
.item-content {
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.item-title {
  font-size: 13px;
  font-weight: 500;
  color: #304156;
}
.item-desc {
  font-size: 12px;
  color: #86909C;
}
.item-icon {
  color: #165DFF;
  font-size: 16px;
}
</style>